package com.fy.tt.executor.node.word.noun;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fy.tt.action.TemplateTool;
import com.fy.tt.remote.service.CoreRemoteService;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class Tool extends Noun {

    CoreRemoteService coreRemoteService = null;

    public String id;
    public String text;

    {
        try {
            coreRemoteService = TemplateTool.getBean(CoreRemoteService.class);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public Tool(String text, Map<String, Object> scriptEnvironment) {
        try {
            init(text, scriptEnvironment);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private void init(String text, Map<String, Object> scriptEnvironment) throws UnsupportedEncodingException {
        if (text.startsWith("\"")) {
            text = text.substring(1, text.length() - 1);
        } else {
            text = text.trim();
        }
        try {
            JSONObject jsonObject = coreRemoteService.getToolByToolName(text);
            if (((int) jsonObject.get("total")) == 0) {
                throw new RuntimeException("查不到该工具信息：" + text);
            }
            JSONArray rows = jsonObject.getJSONArray("rows");
            String toolID = (String) rows.getJSONObject(0).get("toolID");
            this.id = toolID;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public boolean run(String methodName) {
        return super.run(methodName);
    }
}
